package cn.iocoder.yudao.module.erp.controller.admin.accountinfo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.crm.dal.dataobject.product.CrmProductCategoryDO;
import cn.iocoder.yudao.module.crm.dal.mysql.product.CrmProductCategoryMapper;
import cn.iocoder.yudao.module.crm.service.product.CrmProductCategoryService;
import cn.iocoder.yudao.module.erp.controller.admin.common.BaseCost;
import cn.iocoder.yudao.module.erp.controller.admin.costinfo.vo.CostInfoRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.planinfo.vo.PlanInfoRespVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.accountplan.AccountPlanDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.contractinfo.ContractInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.costinfo.CostInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.customerinfo.CustomerInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.planinfo.PlanInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductCategoryDO;
import cn.iocoder.yudao.module.erp.dal.mysql.accountinfo.AccountInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.accountplan.AccountPlanMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.contractinfo.ContractInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.costinfo.CostInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.planinfo.PlanInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.product.ErpProductCategoryMapper;
import cn.iocoder.yudao.module.erp.service.customerinfo.CustomerInfoService;
import cn.iocoder.yudao.module.erp.service.product.ErpProductCategoryService;
import com.alibaba.excel.EasyExcel;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

import cn.iocoder.yudao.module.erp.controller.admin.accountinfo.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.accountinfo.AccountInfoDO;
import cn.iocoder.yudao.module.erp.service.accountinfo.AccountInfoService;

@Tag(name = "管理后台 - 对账单信息")
@RestController
@RequestMapping("/erp/account-info")
@Validated
public class AccountInfoController {

    @Resource
    private AccountInfoService accountInfoService;

    @Resource
    private PlanInfoMapper planInfoMapper;

    @Resource
    private AccountPlanMapper accountPlanMapper;

    @Resource
    private CustomerInfoService customerInfoService;

    @Resource
    private AccountInfoMapper accountInfoMapper;


    @Resource
    private ContractInfoMapper contractInfoMapper;

    @Resource
    private CrmProductCategoryService crmproductCategoryService;

    @Resource
    private ErpProductCategoryService erpProductCategoryService;

    @Resource
    private ErpProductCategoryMapper erpProductCategoryMapper;

    @Resource
    private CrmProductCategoryMapper crmProductCategoryMapper;


    @Resource
    private CostInfoMapper costInfoMapper;

    @PostMapping("/create")
    @Operation(summary = "创建对账单信息")
    @PreAuthorize("@ss.hasPermission('erp:account-info:create')")
    public CommonResult<Long> createAccountInfo(@Valid @RequestBody AccountInfoSaveReqVO createReqVO) {

//文件读取
    /*    String content= FileUtil.readString(new File("D:/down.txt"),"utf-8");
        JSONArray array= JSONUtil.parseArray(content);
        List<ErpProductCategoryDO> downList=new ArrayList<>();
        for(Object a:array){
            //System.out.println(a.toString());
            JSONObject j= JSONUtil.parseObj(a.toString());
            //一级
            if(!j.isEmpty()){
                JSONArray na=j.getJSONArray("upPointList");
                if(na!=null&&na.size()>0){
                    //一级
                    CrmProductCategoryDO lever1=crmProductCategoryMapper.selectByParentIdAndName(0L,j.getStr("pipelineName"));
                    if(lever1==null){
                         lever1=new CrmProductCategoryDO();
                        // lever1.setCode(j.getStr("id"));
                        lever1.setName(j.getStr("pipelineName"));
                        // lever1.setStatus(0);
                        lever1.setParentId(0L);
                        // lever1.setSort(j.getInt("id"));
                        crmProductCategoryMapper.insert(lever1);
                    }

                    //二级
                    CrmProductCategoryDO lever2=new CrmProductCategoryDO();
                    // lever2.setCode(j.getStr("id"));
                    lever2.setName(j.getStr("name"));
                    //  lever2.setStatus(0);
                    lever2.setParentId(lever1.getId());
                    //lever2.setSort(j.getInt("id"));
                    crmProductCategoryMapper.insert(lever2);
                    for(Object son:na){
                        JSONObject sj=JSONUtil.parseObj(son);
                        //三级级
                        CrmProductCategoryDO sons=new CrmProductCategoryDO();
                        // sons.setCode(sj.getStr("id"));
                        sons.setName(sj.getStr("name"));
                       // sons.setStatus(0);
                        sons.setParentId(lever2.getId());
                        // sons.setSort(sj.getInt("id"));
                        crmProductCategoryMapper.insert(sons);
                    }
                }
            }

            if(!j.isEmpty()){
                JSONArray na=j.getJSONArray("downPointList");
                if(na!=null&&na.size()>0){
                    //一级
                    ErpProductCategoryDO lever1=erpProductCategoryMapper.selectByParentIdAndName(0L,j.getStr("pipelineName"));
                    if(lever1==null){
                         lever1=new ErpProductCategoryDO();
                        lever1.setCode(j.getStr("id"));
                        lever1.setName(j.getStr("pipelineName"));
                        lever1.setStatus(0);
                        lever1.setParentId(0L);
                        lever1.setSort(j.getInt("id"));
                        erpProductCategoryMapper.insert(lever1);
                    }
                    //二级

                    ErpProductCategoryDO lever2=new ErpProductCategoryDO();
                    lever2.setCode(j.getStr("id"));
                    lever2.setName(j.getStr("name"));
                    lever2.setStatus(0);
                    lever2.setParentId(lever1.getId());
                    lever2.setSort(j.getInt("id"));
                    erpProductCategoryMapper.insert(lever2);
                    for(Object son:na){
                        JSONObject sj=JSONUtil.parseObj(son);
                        //三级级
                        ErpProductCategoryDO sons=new ErpProductCategoryDO();
                        sons.setCode(sj.getStr("id"));
                        sons.setName(sj.getStr("name"));
                        sons.setStatus(0);
                        sons.setParentId(lever2.getId());
                        sons.setSort(sj.getInt("id"));
                        erpProductCategoryMapper.insert(sons);
                    }
                }
            }


        }*/


        return success(accountInfoService.createAccountInfo(createReqVO));
    }



    @PostMapping("/addCostToAccountInfo")
    @Operation(summary = "对账单添加其他费用")
    @PreAuthorize("@ss.hasPermission('erp:account-info:create')")
    public CommonResult<Long> addCostToAccountInfo(@Valid @RequestBody AccountInfoSaveReqVO createReqVO) {

        return success(accountInfoService.addCostToAccountInfo(createReqVO));
    }



    @PostMapping("/addPlanToAccount")
    @Operation(summary = "添加计划到账单信息")
    @PreAuthorize("@ss.hasPermission('erp:account-info:create')")
    public CommonResult<Long> addPlanToAccount(/*@Valid */@RequestBody AccountInfoSaveReqVO createReqVO) {
        return success(accountInfoService.addPlanToAccount(createReqVO));
    }





    @PutMapping("/update")
    @Operation(summary = "更新对账单信息")
    @PreAuthorize("@ss.hasPermission('erp:account-info:update')")
    public CommonResult<Boolean> updateAccountInfo(@Valid @RequestBody AccountInfoSaveReqVO updateReqVO) {
        accountInfoService.updateAccountInfo(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除对账单信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:account-info:delete')")
    public CommonResult<Boolean> deleteAccountInfo(@RequestParam("id") Long id) {
        accountInfoService.deleteAccountInfo(id);
        return success(true);
    }





    @GetMapping("/getInfoAndCostList")
    @Operation(summary = "获得对账单详情和关联的其他费用")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:account-info:query')")
    public CommonResult<AccountInfoRespVO> getInfoAndCostList(@RequestParam("id") Long id) {
        AccountInfoDO accountInfo = accountInfoService.getAccountInfo(id);

        AccountInfoRespVO vo=BeanUtils.toBean(accountInfo, AccountInfoRespVO.class);
        //得到ids
        //得到关系
        List<CostInfoDO> list=costInfoMapper.selectList(new LambdaQueryWrapperX<CostInfoDO>().eq(CostInfoDO::getAccountId,id));
        //得到ids
       // List<Long> planIds=list.stream().map(e->e.getPlanId()).collect(Collectors.toList());

        if(list!=null&&list.size()>0){
            //得到客户
            List<Long> customerIds=list.stream().map(CostInfoDO::getCustomerId).filter(Objects::nonNull).collect(Collectors.toList());

            List<CustomerInfoDO> customerList = customerInfoService.getCustomerListIds(customerIds);

            Map<Long,CustomerInfoDO> customerMap=customerList.stream().collect(Collectors.toMap(CustomerInfoDO::getId, e -> e));

            List<CostInfoRespVO> rlist=BeanUtils.toBean(list, CostInfoRespVO.class,cost->{
                MapUtils.findAndThen(customerMap, cost.getCustomerId(), cus -> cost.setCustomerName(cus.getName()));
            });
            vo.setCostList(rlist);

        }
        vo.setCustomerName(customerInfoService.getCustomerInfo(vo.getCustomerId()).getName());

        return success(vo);
    }


    @GetMapping("/get")
    @Operation(summary = "获得对账单信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:account-info:query')")
    public CommonResult<AccountInfoRespVO> getAccountInfo(@RequestParam("id") Long id) {
        AccountInfoDO accountInfo = accountInfoService.getAccountInfo(id);

        AccountInfoRespVO vo=BeanUtils.toBean(accountInfo, AccountInfoRespVO.class);

        BigDecimal gasAmount=vo.getAccountMoneyCount();
        BigDecimal costAmount=vo.getCostAmount()==null?new BigDecimal("0"):vo.getCostAmount();
        BigDecimal allAmount=gasAmount.add(costAmount);
        vo.setAllAmount(allAmount);

        List<BaseCost> baseList=new ArrayList<>();
        //得到ids
        //得到关系
        List<AccountPlanDO> list=accountPlanMapper.selectList(new LambdaQueryWrapperX<AccountPlanDO>().eq(AccountPlanDO::getAccountId,id).select(AccountPlanDO::getPlanId));
        //得到ids
        List<Long> planIds=list.stream().map(e->e.getPlanId()).collect(Collectors.toList());

        if(planIds.size()>0){
            List<PlanInfoDO> planInfoDOList=planInfoMapper.selectList(new LambdaQueryWrapperX<PlanInfoDO>().in(PlanInfoDO::getId,planIds).orderByDesc(PlanInfoDO::getNowTime));
            //处理状态

            // 客户信息
            List<Long> customerIds=planInfoDOList.stream().flatMap(item-> Stream.of(item.getBuyCustomerId(),item.getSaleCustomerId())).collect(Collectors.toList());
            List<CustomerInfoDO> customerList = customerInfoService.getCustomerListIds(customerIds);

            Map<Long,CustomerInfoDO> customerMap=customerList.stream().collect(Collectors.toMap(CustomerInfoDO::getId, e -> e));
            //  return success(BeanUtils.toBean(pageResult, PlanInfoRespVO.class));

            //合同信息
            List<Long> contractIds=planInfoDOList.stream().flatMap(item-> Stream.of(item.getBuyContractId(),item.getSaleContractId())).collect(Collectors.toList());
            List<ContractInfoDO> contractInfoDOList = contractInfoMapper.selectList(new LambdaQueryWrapperX<ContractInfoDO>().in(ContractInfoDO::getId,contractIds));

            Map<Long,ContractInfoDO> contractMap=contractInfoDOList.stream().collect(Collectors.toMap(ContractInfoDO::getId, e -> e));

            Map<Long, CrmProductCategoryDO> upMap = crmproductCategoryService.getProductCategoryMap(
                    convertSet(planInfoDOList, PlanInfoDO::getUpId));

            Map<Long, ErpProductCategoryDO> downloadMap = erpProductCategoryService.getProductCategoryMap(
                    convertSet(planInfoDOList, PlanInfoDO::getDownloadId));


            List<PlanInfoRespVO> rlist=BeanUtils.toBean(planInfoDOList, PlanInfoRespVO.class, plan -> {
                MapUtils.findAndThen(customerMap, plan.getBuyCustomerId(), cus -> plan.setBuyCustomerName(cus.getName()));
                MapUtils.findAndThen(customerMap, plan.getSaleCustomerId(), cus -> plan.setSaleCustomerName(cus.getName()));

                MapUtils.findAndThen(contractMap, plan.getBuyContractId(), cus -> plan.setBuyContractName(cus.getName()));

                MapUtils.findAndThen(contractMap, plan.getSaleContractId(), cus -> plan.setSaleContractName(cus.getName()));

                MapUtils.findAndThen(upMap, plan.getUpId(),
                        l -> plan.setUpName(l.getShortName()));

                MapUtils.findAndThen(downloadMap, plan.getDownloadId(),
                        l -> plan.setDownloadName(l.getShortName()));

            });
            vo.setPlanList(rlist);
            baseList.addAll(rlist);
        }
        //得到costList
        List<CostInfoDO> costList=costInfoMapper.selectList(new LambdaQueryWrapperX<CostInfoDO>().eq(CostInfoDO::getAccountId,vo.getId()));
        if(costList!=null&&costList.size()>0){
            List<CostInfoRespVO> rlist=BeanUtils.toBean(costList,CostInfoRespVO.class);
            baseList.addAll(rlist);
        }
        if(baseList.size()>0){
            // 使用自定义比较器对列表进行排序
         /*   baseList.stream().forEach(e->{
                System.out.println(e.getOrderTime()+"\t"+e.getFlag()+"\t");
            });*/
            Collections.sort(baseList, Comparator.comparing(BaseCost::getOrderTime));

            //日期排序
            /*List<BaseCost> sortedList = baseList.stream()
                    .sorted((o1, o2) -> o1.getOrderTime().compareTo(o2.getOrderTime()))
                    .collect(Collectors.toList());*/
            vo.setBaseList(baseList);
        }



        vo.setCustomerName(customerInfoService.getCustomerInfo(vo.getCustomerId()).getName());

        return success(vo);
    }

    @GetMapping("/page")
    @Operation(summary = "获得对账单信息分页")
    @PreAuthorize("@ss.hasPermission('erp:account-info:query')")
    public CommonResult<PageResult<AccountInfoRespVO>> getAccountInfoPage(@Valid AccountInfoPageReqVO pageReqVO) {
        PageResult<AccountInfoDO> pageResult = accountInfoService.getAccountInfoPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty(pageResult.getTotal()));
        }
        // 客户信息
        List<Long> customerIds=pageResult.getList().stream().map(item-> item.getCustomerId()).collect(Collectors.toList());
        List<CustomerInfoDO> customerList = customerInfoService.getCustomerListIds(customerIds);

        Map<Long,CustomerInfoDO> customerMap=customerList.stream().collect(Collectors.toMap(CustomerInfoDO::getId, e -> e));

        return success(BeanUtils.toBean(pageResult, AccountInfoRespVO.class,account -> {
            MapUtils.findAndThen(customerMap, account.getCustomerId(), cus -> account.setCustomerName(cus.getName()));
        }));
    }


    @GetMapping("/findAccountList")
    @Operation(summary = "获得对账单列表")
    public CommonResult<List<AccountInfoRespVO>> findAccountList(@Valid AccountInfoPageReqVO reqVO) {
        List<AccountInfoDO> list=accountInfoMapper.selectList(new LambdaQueryWrapperX<AccountInfoDO>()
                .eqIfPresent(AccountInfoDO::getType, reqVO.getType())
                .eqIfPresent(AccountInfoDO::getCustomerId, reqVO.getCustomerId())
                .eqIfPresent(AccountInfoDO::getAccountGasCount, reqVO.getAccountGasCount())
                .eqIfPresent(AccountInfoDO::getAccountMoneyCount, reqVO.getAccountMoneyCount())
                .betweenIfPresent(AccountInfoDO::getBeginTime, reqVO.getBeginTime())
                .betweenIfPresent(AccountInfoDO::getEndTime, reqVO.getEndTime())
                .betweenIfPresent(AccountInfoDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(AccountInfoDO::getEndTime));

        CustomerInfoDO info=customerInfoService.getCustomerInfo(reqVO.getCustomerId());
        List<AccountInfoRespVO> rlist=BeanUtils.toBean(list, AccountInfoRespVO.class,account -> {
            account.setChooseName(DateUtil.format(account.getBeginTime(),"yyyy-MM-dd")+" 至 "+DateUtil.format(account.getEndTime(),"yyyy-MM-dd"));
            account.setCustomerName(info.getName());
        });
        return success(rlist);



      /*  PageResult<AccountInfoDO> pageResult = accountInfoService.getAccountInfoPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty(pageResult.getTotal()));
        }



        // 客户信息
        List<Long> customerIds=pageResult.getList().stream().map(item-> item.getCustomerId()).collect(Collectors.toList());
        List<CustomerInfoDO> customerList = customerInfoService.getCustomerListIds(customerIds);

        Map<Long,CustomerInfoDO> customerMap=customerList.stream().collect(Collectors.toMap(CustomerInfoDO::getId, e -> e));

        return success(BeanUtils.toBean(pageResult, AccountInfoRespVO.class,account -> {
            MapUtils.findAndThen(customerMap, account.getCustomerId(), cus -> account.setCustomerName(cus.getName()));
        }));*/
    }




  /*  @Resource
    private TenantMapper tenantMapper;*/

    @GetMapping("/export-account-detail-excel")
    @Operation(summary = "导出对账单信息")
    @ApiAccessLog(operateType = EXPORT)
    public void exportAccountInfoDetailExcel(@RequestParam("id") Long id,
                                       HttpServletResponse response) throws IOException {

        AccountInfoDO accountInfo = accountInfoService.getAccountInfo(id);

        AccountInfoRespVO vo=BeanUtils.toBean(accountInfo, AccountInfoRespVO.class);

        BigDecimal gasAmount=vo.getAccountMoneyCount();
        BigDecimal costAmount=vo.getCostAmount()==null?new BigDecimal("0"):vo.getCostAmount();
        BigDecimal allAmount=gasAmount.add(costAmount);
        vo.setAllAmount(allAmount);

        List<BaseCost> baseList=new ArrayList<>();
        //得到ids
        //得到关系
        List<AccountPlanDO> list=accountPlanMapper.selectList(new LambdaQueryWrapperX<AccountPlanDO>().eq(AccountPlanDO::getAccountId,id).select(AccountPlanDO::getPlanId));
        //得到ids
        List<Long> planIds=list.stream().map(e->e.getPlanId()).collect(Collectors.toList());

        if(planIds.size()>0){
            List<PlanInfoDO> planInfoDOList=planInfoMapper.selectList(new LambdaQueryWrapperX<PlanInfoDO>().in(PlanInfoDO::getId,planIds).orderByDesc(PlanInfoDO::getNowTime));
            //处理状态

            // 客户信息
            List<Long> customerIds=planInfoDOList.stream().flatMap(item-> Stream.of(item.getBuyCustomerId(),item.getSaleCustomerId())).collect(Collectors.toList());
            List<CustomerInfoDO> customerList = customerInfoService.getCustomerListIds(customerIds);

            Map<Long,CustomerInfoDO> customerMap=customerList.stream().collect(Collectors.toMap(CustomerInfoDO::getId, e -> e));
            //  return success(BeanUtils.toBean(pageResult, PlanInfoRespVO.class));

            //合同信息
            List<Long> contractIds=planInfoDOList.stream().flatMap(item-> Stream.of(item.getBuyContractId(),item.getSaleContractId())).collect(Collectors.toList());
            List<ContractInfoDO> contractInfoDOList = contractInfoMapper.selectList(new LambdaQueryWrapperX<ContractInfoDO>().in(ContractInfoDO::getId,contractIds));

            Map<Long,ContractInfoDO> contractMap=contractInfoDOList.stream().collect(Collectors.toMap(ContractInfoDO::getId, e -> e));

            Map<Long, CrmProductCategoryDO> upMap = crmproductCategoryService.getProductCategoryMap(
                    convertSet(planInfoDOList, PlanInfoDO::getUpId));

            Map<Long, ErpProductCategoryDO> downloadMap = erpProductCategoryService.getProductCategoryMap(
                    convertSet(planInfoDOList, PlanInfoDO::getDownloadId));


            List<PlanInfoRespVO> rlist=BeanUtils.toBean(planInfoDOList, PlanInfoRespVO.class, plan -> {
              /*  MapUtils.findAndThen(customerMap, plan.getBuyCustomerId(), cus -> plan.setBuyCustomerName(cus.getName()));
                MapUtils.findAndThen(customerMap, plan.getSaleCustomerId(), cus -> plan.setSaleCustomerName(cus.getName()));*/

                MapUtils.findAndThen(contractMap, plan.getBuyContractId(), cus -> plan.setBuyContractName(cus.getName()));

                MapUtils.findAndThen(contractMap, plan.getSaleContractId(), cus -> plan.setSaleContractName(cus.getName()));

                MapUtils.findAndThen(upMap, plan.getUpId(),
                        l -> plan.setUpName(l.getShortName()));

                MapUtils.findAndThen(downloadMap, plan.getDownloadId(),
                        l -> plan.setDownloadName(l.getShortName()));

            });
            vo.setPlanList(rlist);
            baseList.addAll(rlist);
        }
        //得到costList
        List<CostInfoDO> costList=costInfoMapper.selectList(new LambdaQueryWrapperX<CostInfoDO>().eq(CostInfoDO::getAccountId,vo.getId()));
        if(costList!=null&&costList.size()>0){
            List<CostInfoRespVO> rlist=BeanUtils.toBean(costList,CostInfoRespVO.class);
            baseList.addAll(rlist);
        }
        if(baseList.size()>0){
            Collections.sort(baseList, Comparator.comparing(BaseCost::getOrderTime));
            //日期排序
            vo.setBaseList(baseList);
        }
        String tenantName = accountInfoMapper.getTenantNameById(TenantContextHolder.getTenantId());
        List<List<String>> header = new ArrayList<>();
        //vo.setCustomerName(customerInfoService.getCustomerInfo(vo.getCustomerId()).getName());
        CustomerInfoDO customerInfoDO=customerInfoService.getCustomerInfo(vo.getCustomerId());
        vo.setCustomerName(customerInfoDO.getName());
        String cellOne="";
        String cellTwo="对账区间（"+DateUtil.date(vo.getBeginTime()).toString("yyyy年MM月dd日")+"至"+DateUtil.date(vo.getEndTime()).toString("yyyy年MM月dd日")+"）";
        String cellThree="";
        if(accountInfo.getType().equals("1")){
            //采购
            cellOne=customerInfoDO.getName()+"账单";
            cellThree="购气单位："+tenantName;
        }else if(accountInfo.getType().equals("2")){
            cellOne=tenantName+"账单";
            cellThree="购气单位："+customerInfoDO.getName();
        }
        header.add(Arrays.asList(cellOne,cellTwo,cellThree));
             /*  header.add(Arrays.asList(tenant.getName(),tenant.getName(),tenant.getName(),tenant.getName()));*/
        header.add(Arrays.asList(cellOne,
                cellTwo,
                cellThree));

        header.add(Arrays.asList(cellOne,cellTwo,"管道气"));


        /*EasyExcel.write(response.getOutputStream()).head(header)
                .autoCloseStream(false) // 不要自动关闭，交给 Servlet 自己处理
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 基于 column 长度，自动适配。最大 255 宽度
               // .registerWriteHandler(new SelectSheetWriteHandler(head)) // 基于固定 sheet 实现下拉框
                .registerConverter(new LongStringConverter()) // 避免 Long 类型丢失精度
                .sheet("sheet1")
                .doWrite(vo.getPlanList());*/

        // 自定义表头样式
     /*   WriteCellStyle headCellStyle = new WriteCellStyle();
        WriteFont headFont = new WriteFont();
        headFont.setFontHeightInPoints((short) 12);
        headFont.setBold(true);
        headFont.setFontName("Arial");
        headCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        headCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        headCellStyle.setWriteFont(headFont);*/


        // 创建样式策略
      /*  HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(headCellStyle, (List<WriteCellStyle>) null);*/



        EasyExcel.write(response.getOutputStream())
                .head(header)
            /*    .registerWriteHandler(styleStrategy)*/
                .sheet("详细信息")
                .doWrite(vo.getBaseList());


        // 表头数据
      /*  List<List<String>> head = new ArrayList<>();
        head.add(Arrays.asList("列1", "列2", "列3"));


        // 数据内容
        List<List<Object>> data = new ArrayList<>();
        data.add(Arrays.asList("数据1", "数据2", "数据3"));
        data.add(Arrays.asList("数据4", "数据5", "数据6"));


        try {
            // 创建 Excel 写入对象并设置文件路径和名称
            EasyExcel.write(response.getOutputStream())
                    // 设置表头
                    .head(head)
                    // 创建工作表
                    .sheet("Sheet1")
                    // 写入数据
                    .doWrite(data);
        } catch (Exception e) {
            e.printStackTrace();
        }*/


        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("对账单", StandardCharsets.UTF_8.name()));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");


    /*    ExcelUtils.write();*/

        // 导出 Excel
       /* ExcelUtils.write(response, "对账单信息.xls", "数据", AccountInfoRespVO.class,
                BeanUtils.toBean(list, AccountInfoRespVO.class,account->{
                    MapUtils.findAndThen(customerMap, account.getCustomerId(), cus -> account.setCustomerName(cus.getName()));
                }));*/

    }


    @GetMapping("/export-excel")
    @Operation(summary = "导出对账单信息 Excel")
    @PreAuthorize("@ss.hasPermission('erp:account-info:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportAccountInfoExcel(@Valid AccountInfoPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<AccountInfoDO> list = accountInfoService.getAccountInfoPage(pageReqVO).getList();

        // 客户信息
        List<CustomerInfoDO> customerList = customerInfoService.getCustomerListIds(
                convertSet(list, AccountInfoDO::getCustomerId));
        Map<Long,CustomerInfoDO> customerMap=customerList.stream().collect(Collectors.toMap(CustomerInfoDO::getId, e -> e));

        // 导出 Excel
        ExcelUtils.write(response, "对账单信息.xls", "数据", AccountInfoRespVO.class,
                        BeanUtils.toBean(list, AccountInfoRespVO.class,account->{
                            MapUtils.findAndThen(customerMap, account.getCustomerId(), cus -> account.setCustomerName(cus.getName()));
                        }));
    }

}